/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ru.miit.elearning.servlets;

import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.hibernate.Session;
import ru.miit.elearning.hibernate.dto.CurriculumLevel;
import ru.miit.elearning.hibernate.dao.CourseDAO;
import ru.miit.elearning.hibernate.dao.DocumentDAO;
import ru.miit.elearning.hibernate.dao.HibernateUtil;

/**
 *
 * @author Cyclone
 */
public class AddCourseServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        Session session = null;
        String message = "";
        boolean completable = true;
        try {


            // all we take from request
            String courseTitle = null;
            String courseNumberString = null;
            String description = null;
            String directionString = null;
            String newDirectionTitle = null;

            FileItem fileItem = null;
            String attachTitle = null;

            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (!isMultipart) {
                courseTitle = request.getParameter("courseTitle");
                courseNumberString = request.getParameter("courseNumber");
                description = request.getParameter("description");
                directionString = request.getParameter("direction");
                newDirectionTitle = request.getParameter("newDirection");
            } else {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List<FileItem> items = upload.parseRequest(request);


                for (FileItem item : items) {
                    if (item.isFormField()) {
                        final String utf8 = "UTF-8";
                        if (courseTitle == null && item.getFieldName().equals("courseTitle")) {
                            courseTitle = item.getString(utf8);
                            continue;
                        }
                        if (courseNumberString == null && item.getFieldName().equals("courseNumber")) {
                            courseNumberString = item.getString(utf8);
                            continue;
                        }
                        if (description == null && item.getFieldName().equals("description")) {
                            description = item.getString(utf8);
                            continue;
                        }
                        if (directionString == null && item.getFieldName().equals("direction")) {
                            directionString = item.getString(utf8);
                            continue;
                        }
                        if (newDirectionTitle == null && item.getFieldName().equals("newDirection")) {
                            newDirectionTitle = item.getString(utf8);
                            continue;
                        }
                        if (newDirectionTitle == null && item.getFieldName().equals("attachTitle")) {
                            attachTitle = item.getString(utf8);
                            continue;
                        }
                    } else {
                        fileItem = item;
                    }
                }
            }

            // courseTitle = request.getParameter("courseTitle");
            if (courseTitle == null || courseTitle.trim().equals("")) {
                message = "Название курса не введено<br/>";
                completable = false;
            }


            //String courseNumberString = request.getParameter("courseNumber");
            Integer courseNumber = null;
            if (courseNumberString != null && courseNumberString.length() > 0) {
                try {
                    courseNumber = Integer.parseInt(courseNumberString);
                } catch (Exception e) {
                    message += "Номер курса указан неверно<br/>";
                    e.printStackTrace();
                }
            }
            courseNumberString = null;

            // description = request.getParameter("description");

            Integer direction = null;
            try {
                //direction = Integer.parseInt(request.getParameter("direction"));
                direction = Integer.parseInt(directionString);
            } catch (Exception e) {
                message += "Укажите направление, к которому относится курс<br/>";
                completable = false;
                e.printStackTrace();
            }

            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();

            CourseDAO courseDAO = new CourseDAO(session);


            CurriculumLevel parentDirectionCurriculumLevel = null;
            if (direction == -1 && completable) {
                // newDirectionTitle = request.getParameter("newDirection");
                if (newDirectionTitle == null) {
                    message += "Укажите название нового направления<br/>";
                    completable = false;
                } else {
                    parentDirectionCurriculumLevel = courseDAO.addDirection(newDirectionTitle);
                    if (parentDirectionCurriculumLevel == null) {
                        message += "Ошибка создания нового направления<br/>";
                        completable = false;
                    } else {
                        direction = parentDirectionCurriculumLevel.getId();
                        message += "Направление \"" + newDirectionTitle + "\" создано<br/>";
                    }
                }
            }


            if (completable) {
                CurriculumLevel courseCurriculumLevel = courseDAO.addCourse(direction, courseTitle, courseNumber, description);

                message += "Курс №" + courseCurriculumLevel.getNumeral() + " \"" + courseCurriculumLevel.getTitle() + "\" добавлен к направлению \"" + courseCurriculumLevel.getCurriculumLevel().getTitle() + "\"";
                message += " : <a href='Course?id=" + courseCurriculumLevel.getId() + "' title='Подробнее о курсе'>редактировать</a>";

                Integer userId = null;
                if (!request.isUserInRole("admin") && request.isUserInRole("tutor")) {
                    userId = courseDAO.findUserIdByLogin(request.getRemoteUser());
                    courseDAO.signTutorOnCourse(userId, courseCurriculumLevel.getId());
                    message += "<p>Курс добавлен к списку проверяемых : <a href='SignStudents?courseId=" + courseCurriculumLevel.getId() + "'>зачислить студентов</a></p>";
                }


                if (fileItem != null) {
                    try {
                        DocumentDAO documentDAO = new DocumentDAO(session);
                        Integer docId = documentDAO.addCurriculumDocument(courseCurriculumLevel.getId(), (attachTitle != null && attachTitle.length() > 0 ? attachTitle : fileItem.getName()));
                        documentDAO.addDocumentVersion(docId, null, fileItem.getInputStream(), documentDAO.findUserIdByLogin(request.getRemoteUser()), fileItem.getName(), fileItem.getContentType(), null);
                    } catch (Exception e) {
                        e.printStackTrace();
                        message += "<br/>Не удалось приложить файл";
                    }
                }

                if (session != null && session.isOpen()) {
                    session.getTransaction().commit();
                }
            }

            getServletContext().setAttribute("message", message);
            response.sendRedirect("Courses");

        } catch (Exception e) {
            if (session != null && session.isOpen()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
            message += "Ошибка создания курса";

            getServletContext().setAttribute("message", message);
            response.sendRedirect("Courses");
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
